package l2s.gameserver.scripts.ai;

import l2s.commons.util.Rnd;
import l2s.gameserver.ThreadPoolManager;
import l2s.gameserver.datatables.NpcTable;
import l2s.gameserver.model.L2Spawn;
import l2s.gameserver.model.Location;
import l2s.gameserver.model.actor.L2Npc;
import l2s.gameserver.scripting.ScriptFile;
import l2s.gameserver.templates.chars.L2NpcTemplate;

public class MasterToma extends AbstractNpcAI implements ScriptFile
{
	
	private static int MASTER_TOMA = 30556;
	private static Location[] spawnLoc =
	{
		new Location(151680, -174891, -1807, 41400),
		new Location(154153, -220105, -3402),
		new Location(178834, -184336, -352)
	};
	private static long TELEPORT_PERIOD = 30 * 60 * 1000; // 30 min
	private static L2Npc masterToma = null;
	protected static boolean isSpawned = false;
	
	public MasterToma(String name, String descr)
	{
		super(name, descr);
		ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(new Runnable()
		{
			@Override
			public void run()
			{
				try
				{
					if (isSpawned)
					{
						onSpawn(false);
					}
					else
					{
						onSpawn(true);
					}
				}
				catch (Exception e)
				{
				}
			}
		}, 1000L, TELEPORT_PERIOD);
	}
	
	protected static void onSpawn(boolean start)
	{
		if ((masterToma != null) && !start)
		{
			masterToma.deleteMe();
		}
		L2NpcTemplate template = NpcTable.getInstance().getTemplate(MASTER_TOMA);
		Location loc = spawnLoc[Rnd.get(spawnLoc.length)];
		try
		{
			L2Spawn spawn = new L2Spawn(template);
			spawn.setHeading(loc.getHeading());
			spawn.setLocx(loc.getX());
			spawn.setLocy(loc.getY());
			spawn.setLocz(loc.getZ() + 20);
			spawn.stopRespawn();
			masterToma = spawn.getLastSpawn();
			masterToma.spawnMe();
			isSpawned = true;
		}
		catch (SecurityException | ClassNotFoundException | NoSuchMethodException e)
		{
			_log.warn("Could not spawn Npc " + MASTER_TOMA);
		}
	}
	
	public static MasterToma getInstance()
	{
		return SingletonHolder._instance;
	}
	
	private static class SingletonHolder
	{
		
		protected static final MasterToma _instance = new MasterToma("MasterToma", "ai");
	}
	
	public static void onLoad()
	{
		getInstance();
	}
}
